package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.presentation.controller.user;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;

import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.presentation.controller.user.devicedata.DeviceDataBean;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.presentation.controller.util.PresentationUtil;

/**
 * Se usa para que cada vista pueda ver datos de un dispositivo distinto de lo contrario
 * todas la vistas leerian de la misma vista porque userSelectionBean tiene alcance de sesion
 * Hay que analizar por una mejor solucion al problema 
 * 
 * Este Bean es utilizado en las vistas
 * simpleuser/devicedata.xhtml
 */
@ManagedBean(name="deviceInfoBean")
@ViewScoped
public class DeviceInfoBean {


	@ManagedProperty(value="#{flash.selectedDevice}")
	private DeviceDataBean selectedDevice;

	@PostConstruct
	public void init(){
		if(selectedDevice != null)
			PresentationUtil.addDeviceToCurrentView(selectedDevice.getDeviceService());
	}
	
	@PreDestroy
	public void finalize(){
		if(selectedDevice != null)
			PresentationUtil.removeDeviceToCurrentView(selectedDevice.getDeviceService());
	}
	

	public void forwardDevicesIfNotSelection(ComponentSystemEvent cse) {
		FacesContext faceContext = FacesContext.getCurrentInstance();
		if (selectedDevice == null) {
			faceContext.getApplication().getNavigationHandler().
		handleNavigation(faceContext, null,	"/simpleuser/listdevices?faces-redirect=true");
		}
	}
	
	public void setSelectedDevice(DeviceDataBean dev) {
		this.selectedDevice = dev;
	}
	
	public DeviceDataBean getSelectedDevice() {
		return selectedDevice;
	}

}
